<?php

namespace Beerus\Modules\Wiki\Controllers;

use App\Admin\Extensions\Tools\GridView;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\cache\wiki\TbkGoods;
use Biz\model\wiki\Wiki as mWiki;
use Biz\pockets\export\ExportData;
use Biz\service\wiki\AdmWiki;
use Biz\service\wiki\AdmWikiPortrait;
use Biz\service\wiki\AdmWikiTag;
use Biz\tools\RealUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;

/**
 * wiki商品画像
 */
class WikiPortraitController extends Controller
{
    const SOURCE_CATEGORY_LIST = '/admin/extend/category/child';

    public function __construct()
    {
        parent::__construct();
    }

    public function screenList(Request $request, Content $content)
    {
        $requestParams = $request->all();
        $category_id = $requestParams['category_id'] ?? 0;
        $second_category_id = $requestParams['second_category_id'] ?? 0;
        $third_category_id = $requestParams['third_category_id'] ?? 0;
        $pageSize = $request->input("per_page", 10);
        $page = $request->input("page", 1);

        $requestParams['page'] = $page;
        $requestParams['per_page'] = $pageSize;

        $query = $this->_filter_request($requestParams);

        list($list, $total) = AdmWikiPortrait::getScreenList($requestParams);
        $styleList = AdmWikiTag::getStyleList();
        $styleList = array_combine($styleList, $styleList);
        Admin::script($this->adminScript($requestParams));
        $gridModel = new pGridDataModel($list, $total, ['perPage' => $pageSize]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel, $category_id, $request, $second_category_id, $third_category_id, $query, $styleList) {
                $grid->paginate($gridModel->getPerPage());
                $grid->filter(function ($filter) use ($category_id, $request, $second_category_id, $third_category_id, $styleList) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function (\Encore\Admin\Grid\Filter $filter) use ($category_id, $second_category_id, $third_category_id, $styleList) {
                        $filter->dropDown('wiki_value', [
                            'title' => '商品名称',
                            'wiki_id' => '商品ID',
                            'basic_id' => 'wikiID',
                            'channel_spu_id' => '第三方商品id'
                        ]);
                        $topCategory = AdmWiki::admGetChildCategoryMap(0);
                        ksort($topCategory);
                        $filter->equal('category_id', '商城类目(一级)')->select($topCategory)->load('second_category_id',
                            self::SOURCE_CATEGORY_LIST);

                        $secondCategory = $category_id > 0 ? AdmWiki::admGetChildCategoryMap($category_id) : [];
                        $filter->equal('second_category_id',
                            '商城类目(二级)')->select($secondCategory)->load('third_category_id',
                            self::SOURCE_CATEGORY_LIST);

                        $thirdCategory = $second_category_id > 0 ? AdmWiki::admGetChildCategoryMap($second_category_id) : [];
                        $filter->equal('third_category_id',
                            '商城类目(三级)')->select($thirdCategory)->load('four_category_id',
                            self::SOURCE_CATEGORY_LIST);
                        $fourCategory = $third_category_id > 0 ? AdmWiki::admGetChildCategoryMap($third_category_id) : [];
                        $filter->equal('four_category_id', '商城类目(四级)')->select($fourCategory);

                        $filter->equal('channel_type', '商品来源')->multipleSelect(mWiki::CHANNEL_TYPE_MAP);
                        $filter->equal('channel_spu_status', '商品第三方状态')->select(mWiki::CHANNEL_STATUS_ARR);
                        $filter->equal('status', '审核状态')->select(mWiki::ADM_STATUS_MAP);
                        $filter->equal('wiki_type', 'wiki类型')->multipleSelect(AdmWikiPortrait::WIKI_TYPE_OPTION);
                        $filter->equal('wiki_basic_style', '风格标签')->select($styleList);
                    });

                    $filter->column(1 / 2,
                        function (\Encore\Admin\Grid\Filter $filter) use ($category_id, $second_category_id, $third_category_id) {
                            $filter->equal('price_tag', '价格属性')->multipleSelect(AdmWikiPortrait::PRICE_TAG_OPTION);
                            $filter->between('date_time', '创建时间')->date();
                            $filter->between('note_cnt', '关联note数');
                            $filter->between('fav_cnt', '被收藏数');
                            $filter->between('buy_cnt', '去购买数');
                            $filter->between('goods_click_cnt', '商品渠道点击');
                            $filter->between('goods_ctr', '商品渠道ctr');
                            $filter->between('content_click_cnt', '内容渠道点击');
                            $filter->between('content_cvr', '内容渠道cvr')->decimal();

                        });
                    $filter->expand();//默认展开
                });
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->tools(function ($tools) use ($query) {
                    $tools->append(new GridView());
                    $tools->append('<div class="btn-group" style="margin-right: 10px">
<a class="btn btn-sm btn-twitter" title="导出下载" href="' . url('/admin/wiki/screen/export?' . $query) . '" target="_blank">
<i class="fa fa-download"></i><span class="hidden-xs">导出/下载</span></a></div>');
                    $tools->append('<div class="btn-group download" style="margin-right: 10px">
<a class="btn btn-sm btn-twitter" title="导出邮件" target="_blank">
<i class="fa fa-envelope"></i><span class="hidden-xs">导出/邮件</span></a></div>');
                });

                $grid->column('id', '商品ID')->display(function () {
                    $html = '<ul class="list-unstyled">';
                    $html .= '<li>' . $this->id . '</li>';
                    $html .= '<li><a href="javascript:void(0);" class="grid-column-copyable text-muted" data-content="' . $this->url . '" title="Copied!" data-placement="bottom"><i class="fa fa-copy"></i></a>';
                    $html .= '<a target="_blank" href="' . $this->url . '">链接</a></li>';
                    $html .= '<li><a target="_blank" href="' . admin_url('/wiki/shareWiki?wiki_id=' . $this->id) . '">关联数:' . $this->relate_num . '</a></li>';
                    $html .= '<li><a target="_blank" href="' . admin_url('/album/albumcheck?wiki_id=' . $this->id) . '">关联清单数:' . $this->album_count . '</a></li>';
                    $html .= '</ul>';
                    return $html;
                })->width(100);
                $grid->column('basic_id', 'WIKI ID')->display(function () {
                    $html = '<ul class="list-unstyled">';
                    $html .= '<li>' . $this->basic_id . '</li>';
                    if ($this->is_official) {
                        $html .= '<li><span class="label label-success">官方</span></li>';
                        if ($this->is_default) {
                            $html .= '<li><span class="label label-info">默认</span></li>';
                        }
                    }
                    $html .= '</ul>';
                    return $html;
                })->width(70);
                $grid->column('title', '商品名称')->width(120);
                $grid->column('hot', '热度/价格')->display(function () {
                    $html = '<ul class="list-unstyled">';
                    $html .= '<li>热度：' . $this->hot . '</li>';
                    $html .= '<li>最低价：' . $this->min_price . '</li>';
                    $html .= '<li>最高价：' . $this->max_price . '</li>';
                    $html .= '<li>收藏数：' . $this->fav_count . '</li>';
                    $html .= '</ul>';
                    return $html;
                })->width(120);
                $grid->column('card_img', '首图')->width(200)->display(function () {
                    $imgPath = $this->cover_img;
                    $image = strlen($imgPath) ? "<img src='" . $imgPath . "' style='width:150px;height:150px;' class='img img-thumbnail' />" : "";
                    $html = '';
                    if ($image) {
                        $html .= '<a href="javascript:layer.open({type: 2,shadeClose: true,title: \'预览\',maxmin: true,area: [\'800px\', \'600px\'],content: \'' . $imgPath . '\'});">';
                        $html .= $image;
                        $html .= '</a>';
                    }
                    return $html;
                })->width(150);
                $grid->column('channel_brand', '品牌名称')->width(150);
                $grid->column('channel_shop_name', '店铺名称')->display(function () {
                    $html = '<ul class="list-unstyled">';
                    $html .= '<li>' . $this->channel_shop_name . '</li>';
                    $channelShopUrl = RealUrl::getShopUrl($this->channel_type, $this->channel_shop_id, $this->channel_seller_id);
                    if ($channelShopUrl) {
                        $html .= '<li><a href="javascript:void(0);" class="grid-column-copyable text-muted" data-content="' . $channelShopUrl . '" title="Copied!" data-placement="bottom"><i class="fa fa-copy"></i></a>';
                        $html .= '<a target="_blank" href="' . $channelShopUrl . '">店铺链接</a></li>';
                    }
                    $html .= '</ul>';
                    return $html;
                })->width(150);
                $grid->column('channel_spu_status', '渠道/状态')->display(function () {
                    $html = '<ul class="list-unstyled">';
                    if ($this->channel_type) {
                        $html .= '<li><span>' . mWiki::CHANNEL_TYPE_MAP[$this->channel_type] . '</span></li>';
                    }
                    $labelStyle = ($this->channel_spu_status == mWiki::CHANNEL_SPU_STATUS_OFF) ? 'danger' : 'success';
                    $labelSapn = ($this->channel_spu_status == mWiki::CHANNEL_SPU_STATUS_OFF) ? '失效' : '有效';
                    $html .= '<li><span class="label label-' . $labelStyle . '">' . $labelSapn . '</span></li>';
                    if ($this->channel == mWiki::CHANNEL_TAOBAO) {
                        $isTbkArr = TbkGoods::isTbkGoods([$this->channel_spu_id]);
                        if ($isTbkArr[$this->channel_spu_id]) {
                            $html .= '<li><span class="label label-info">淘宝客</span></li>';
                        }
                    }
                    $html .= '</ul>';
                    return $html;
                })->width(90);
                //$grid->column('addtime', '创建时间')->width(100);
                //$grid->column('status_desc', '状态')->width(70);
                //$grid->column('category_desc', '类目')->width(100);
                $grid->column('price_tag', '价格属性')->width(50);
                $grid->column('note_cnt', '关联note数')->width(50);
                $grid->column('fav_cnt', '被收藏数')->width(50);
                $grid->column('buy_cnt', '去购买数')->width(50);
                $grid->column('goods_click_cnt', '商品渠道点击')->width(50);
                $grid->column('goods_ctr', '商品渠道ctr')->width(50);
                $grid->column('content_click_cnt', '内容渠道点击')->width(50);
                $grid->column('content_cvr', '内容渠道cvr')->width(50);
                $grid->column('wiki_basic_style', '风格标签')->width(50);

                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                    $tabType = 1;
                    if ($actions->row->brand_id > 0) {
                        $tabType = 2;
                    } elseif ($actions->row->store_id > 0) {
                        $tabType = 3;
                    }
                    $actions->prepend('&nbsp;<a class="fa fa-circle" target="_blank" href="' . url('/admin/wiki/admList?wiki_id=' . $actions->row->id . '&tab_type=' . $tabType) . '">商品相关操作</a>');
                    if ($actions->row->channel != mWiki::CHANNEL_NOTHING) {
                        $actions->prepend('<a class="fa fa-link" target="_blank" href="' . $actions->row->url . '">链接</a>');
                    }
                    $actions->prepend('<a class="fa fa-envelope" href="javascript:layer.open({
                                type: 2,
                                title: \'预览\',
                                maxmin: true,
                                area: [\'800px\', \'500px\'],
                                content: \'' . $actions->row->h5_url . '\'
                            });">预览</a>');
                });
            }
        );
        return $content
            ->header('wiki商品筛选')
            ->description(' ')
            ->row($gridList);
    }

    public function screenExport(Request $request)
    {
        ini_set('memory_limit', '1024M');
        $requestParams = $request->all();
        $pageSize = $request->input("per_page", 10);
        $page = $request->input("page", 1);
        $requestParams['page'] = $page;
        $requestParams['per_page'] = $pageSize;
        $downMail = $request->input("down_mail", 0);

        if ($downMail) {
            $status = 1;
            $message = '导出商品将发送至邮箱,请稍后查看';
            try {
                $adminEmail = Admin::user()->email;
                if (empty($adminEmail)) {
                    throw new \Exception('导出商品将发送至邮箱(' . $adminEmail . '),请先设置邮箱');
                }
                //发送邮件
                ExportData::addTask([AdmWikiPortrait::class, 'admExportScreenList'], [$requestParams, $adminEmail]);
            } catch (\Exception $e) {
                $message = $e->getMessage();
                $status = 0;
            }
            return response()->json(compact('status', 'message'));
        } else {
            AdmWikiPortrait::admExportScreenList($requestParams);
        }
    }


    private function _filter_request($requestParams)
    {
        unset($requestParams['_pjax']);
        return http_build_query($requestParams);
    }

    private function adminScript($requestParams)
    {
        $requestParams['down_mail'] = 1;
        $query = $this->_filter_request($requestParams);
        return <<<SCRIPT
        $('.grid-table').on('click', '.grid-column-copyable', (function (e) {
            var content = $(this).data('content');
            var temp = $('<input>');
            $("body").append(temp);
            temp.val(content).select();
            document.execCommand("copy");
            temp.remove();
            $(this).tooltip('show');
        }));
        var singleDownLoad = true;
        $('.download').unbind('click').click(function(){
            if (singleDownLoad == false) {
                return;
            }
            singleDownLoad = false;
            sign = 1
            if (sign > 0) {
                $.ajax({
                    url:'/admin/wiki/screen/export?$query',
                    type:"GET",
                    dataType:"json",
                    success:function(result){
                        if (result.status) {
                            toastr.success(result.message);
                        } else {
                            toastr.warning(result.message);
                        }
                    },
                    complete : function(){
                        singleDownLoad = true;
                    },
                    error:function(){
                        toastr.error('系统错误,请联系管理员');
                    }
                });
            }
         });
SCRIPT;
    }

    private function clipboardHtml($id)
    {
        return "<span style='cursor: pointer;'><i class='fa fa-clipboard copyBtn'  data-clipboard-target='#{$id}'></i></span>";
    }
}
